package com.weixin.common.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import javax.swing.*;

/**
 * @version 1.0.0
 * @className: SpringBeanUtil
 * @description: SpringBean工具类
 * @author: zhangjunfa
 * @date: 2023/6/9 9:40
 */
@Component
public class SpringBeanUtil implements BeanFactoryPostProcessor {

    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringBeanUtil.beanFactory = beanFactory;
    }

    /**
     * 获取Spring注册的Bean对象
     *
     * @param name bean的名称
     * @param <T>  bean的类型
     * @return 注册的bean的实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取Spring注册的Bean对象
     *
     * @param clazz bean的类
     * @param <T>   bean的类型
     * @return 注册的bean的实例
     * @throws BeansException
     */
    public static <T> T getBean(Class<T> clazz) throws BeansException {
        return beanFactory.getBean(clazz);
    }

    /**
     * 获取Spring注册的Bean对象
     *
     * @param name  bean的名称
     * @param clazz bean类
     * @param <T>   bean的类型
     * @return Spring注册的Bean实例
     * @throws BeansException
     */
    public static <T> T getBean(String name, Class<T> clazz) throws BeansException {
        return beanFactory.getBean(name, clazz);
    }
}
